package com.btb.adapter.utils;

import static java.util.stream.Collectors.toList;

import java.util.Arrays;
import java.util.List;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 */
@Component
public class SpringContextUtil implements ApplicationContextAware {

	/**
	 * Spring应用上下文环境
	 */
	private static ApplicationContext applicationContext;

	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	@Override
	public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
		SpringContextUtil.applicationContext = applicationContext;
	}

	@SuppressWarnings("unchecked")
	public static <T> T getBean(final String name) throws BeansException {
		return (T) applicationContext.getBean(name);
	}

	public static <T> String[] getBeanNamesForType(Class<T> clazz) {
		return applicationContext.getBeanNamesForType(clazz);
	}

	@SuppressWarnings("unchecked")
	public static <T> List<T> getBeanForType(Class<T> clazz) {
		String[] beanNamesForType = getBeanNamesForType(clazz);
		List<T> collect = (List<T>) Arrays.stream(beanNamesForType).map(SpringContextUtil::getBean).collect(toList());
		return collect;
	}

	public static <T> T getBean(final Class<T> clazz) throws BeansException {
		return applicationContext.getBean(clazz);
	}

}
